package com.bw.medical.realtime.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.bw.medical.realtime.app.dws.TransientSink;


import java.lang.reflect.Field;

public class Bean2JSONUtil {

    public static <T> String bean2JSON(T obj) throws IllegalAccessException {
        Class<?> clazz = obj.getClass();

        Field[] fields = clazz.getDeclaredFields();

        JSONObject jsonObj = new JSONObject();

        for (Field field : fields) {
            TransientSink transientSink = field.getAnnotation(TransientSink.class);
            if (transientSink == null) {
                field.setAccessible(true);
                String name = field.getName();
                Object value = field.get(obj);

                StringBuilder snakeCaseName = new StringBuilder();
                for (int i = 0; i < name.length(); i++) {
                    char curChar = name.charAt(i);
                    if (Character.isUpperCase(curChar)) {
                        snakeCaseName.append("_");
                        curChar = Character.toLowerCase(curChar);
                    }
                    snakeCaseName.append(curChar);
                }

                name = snakeCaseName.toString();
                jsonObj.put(name, value);
            }
        }

        return JSON.toJSONString(jsonObj);
    }
}